package us.icitap.cm.ui.shared;

import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;

import us.icitap.cm.CaseManagementUI;
import us.icitap.cm.business.entities.Case;
import us.icitap.cm.listeners.ReturnObjectListener;
import us.icitap.cm.ui.custom.CustButton;
import us.icitap.cm.ui.custom.CustSearchButton;
import us.icitap.cm.ui.custom.CustTextField;
import us.icitap.cm.ui.custom.CustWindow;
import us.icitap.cm.utils.HandleNotification;
import us.icitap.utils.Result;

public class LoadCaseWindow extends CustWindow {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4216259270176571005L;
	
	
	
	private final CustTextField caseIdTextField = new CustTextField("Kodi i ceshtjes");
	private final CustSearchButton searchButton = new CustSearchButton("Ngarko ceshtje");
	private final CustButton newCaseButton = new CustButton("Krijo ceshtje");
	
	public LoadCaseWindow(boolean newCaseEnabled) {
		

		
		this.setCaption("Ngarko ceshtje");
		HorizontalLayout hl = new HorizontalLayout();
		hl.setMargin(true);
		hl.setSpacing(true);
		hl.addComponent(caseIdTextField);
		this.caseIdTextField.focus();
		hl.addComponent(searchButton);
		hl.setComponentAlignment(searchButton, Alignment.BOTTOM_RIGHT);
		
		if(newCaseEnabled){
			hl.addComponent(newCaseButton);
			hl.setComponentAlignment(newCaseButton, Alignment.BOTTOM_RIGHT);
			this.newCaseButton.addClickListener(new ClickListener() {
				
				@Override
				public void buttonClick(ClickEvent event) {
					if(returnObjectListener != null)
						returnObjectListener.returnObject(new Case(CaseManagementUI.getUser().getUsername()));
					
				}
			});
			
		}
		
		
		
		this.setContent(hl);
		
		this.searchButton.addClickListener(new ClickListener() {
			
			@Override
			public void buttonClick(ClickEvent event) {
				Result<Case> result = CaseManagementUI.appStatelessBean.getPersistenceBean().findCaseById(caseIdTextField.getValue());
				if(result.isSucceeded()){
					
					if( result.getObject() != null && returnObjectListener != null)
						returnObjectListener.returnObject(result.getObject());
					else if(result.getObject() == null){
						HandleNotification.showInfoOnTray(result.getMessage());
					}
				}
				else
					HandleNotification.showErrorOnScreen(result.getMessage());
				
				
				
			}
		});
		
		
		
	}

	private ReturnObjectListener returnObjectListener;
	
	public void addListener(ReturnObjectListener listener){
		this.returnObjectListener = listener;
		
	}
	
}
